package com.education.wisdom.controller;

import com.education.common.utils.LogUtil;
import com.education.wisdom.pojo.CurrencyRecord;
import com.education.wisdom.pojo.StudentClass;
import com.education.wisdom.pojo.SysAppLogin;
import com.education.wisdom.pojo.TeacherClass;
import com.education.wisdom.service.*;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.List;

import static com.education.common.core.BaseController.writeJSON;


/**
 * @author : 闫清
 * @date : Created in 17:51 2018/10/24
 */
@Controller
@CrossOrigin
@ResponseBody
@Slf4j
@RequestMapping("/web/index")
@Api(tags = {"登录注册板块"})
public class FullIndexController {

    @Autowired
    private ISysAppLoginService SysAppLoginService;

    @Autowired
    private IUserAccountService userAccountService;

//    @Autowired
//    private AuthenticationManager authenticationManager;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private IStudentClassService studentClassService;

    @Autowired
    private ITeacherClassService teacherClassService;
    @Autowired
    private IJrLogininforService jrLogininforService;
    @Autowired
    private ICurrencyRecordService currencyRecordService;


    /**
     * 登录
     *
     * @param phone    用户名
     * @param password 密码
     * @return 结果
     */
//    @Transactional
//    @PostMapping("/checkLogin")
//    @ApiOperation("登录")
//    @ApiImplicitParams({
//            @ApiImplicitParam(name = "phone", value = "登录账号", required = true, dataType = "String"),
//            @ApiImplicitParam(name = "password", value = "登录密码", required = true, dataType = "String")})
//    public void checkLogin(HttpServletRequest request, HttpServletResponse response, HttpSession session, String phone, String password) throws Exception {
//        log.info(LogUtil.LogInfo("登录", new Date()));
//        if (phone != null && password != null) {
//            Map<String, Object> map = new HashMap<>();
//            map.put("username", phone);
//            map.put("password", Token.encoderByMd5(password));
//            SysAppLogin user = SysAppLoginService.selectSysAppLogin(map);
//            response.setHeader("Access-Control-Allow-Credentials", "true");
//            if (user != null) {
//                if (user.getUserState() == 0) {
//                    Integer logins = user.getLogins();
//                    JrLogininfor logininfor = new JrLogininfor();
//                    logininfor.setLoginName(phone);
//                    List<JrLogininfor> loginfor = jrLogininforService.selectLogininforList(logininfor);
//                    int sum = loginfor.size();
//                    if (sum < logins) {
//                        JrLogininfor lfor = new JrLogininfor();
//                        lfor.setLoginName(phone);
//                        lfor.setLoginTime(new Date());
//                        jrLogininforService.insertLogininfor(lfor);
//                        JwtAuthenticatioToken token = SecurityUtils.login(request, phone, password, authenticationManager);
//                        user.setToken(token.getToken());
//                        user.setUserPassword(null);
//                        session.setAttribute("user", user);
//                        writeJSON(user, response, "200", "true");
//                    } else {
//                        writeJSON("您的账号超过登录次数！", response, Constant.LOGIN_FAILURE, "true");
//                    }
//                } else if (user.getUserState() == 1) {
//                    writeJSON("您的账号异常，请及时联系管理员！", response, "201", "true");
//                } else if (user.getUserState() == 2) {
//                    writeJSON("您的账号被加入黑名单，请及时联系管理员！", response, "201", "true");
//                }
//            } else {
//                writeJSON("用户名或密码输入错误", response, "201", "false");
//            }
//        } else {
//            writeJSON("信息不完整", response, "201", "false");
//        }
//
//    }

    /**
     * 注册
     */
//    @PostMapping("/userLogin")
//    @ApiOperation("注册")
//    @ApiImplicitParams({
//            @ApiImplicitParam(name = "userPhone", value = "登录账号", required = true, dataType = "String"),
//            @ApiImplicitParam(name = "userPassword", value = "登录密码", required = true, dataType = "String"),
//            @ApiImplicitParam(name = "code", value = "验证码", required = true, dataType = "String")})
//    public void userLogin(HttpServletResponse response, SysAppLogin sysAppLogin, String code) throws Exception {
//        log.info(LogUtil.LogInfo("注册", new Date()));
//        //缓存取出验证码
//        String s = redisTemplate.boundValueOps(sysAppLogin.getUserPhone()).get();
//        if (s != null) {
//            if (code.equals(s)) {
//                sysAppLogin.setUserId(UUIDUtils.getByUUId());
//                sysAppLogin.setUserPassword(Token.encoderByMd5(sysAppLogin.getUserPassword()));
//                sysAppLogin.setUserState(0);
//                sysAppLogin.setUserIco("http://39.98.63.21:60/img/001.png");
////                sysAppLogin.setUserCreatedate(new Timestamp(new Date().getTime()));
//                sysAppLogin.setUserCreatedate(new Timestamp(System.currentTimeMillis()));
//                UserAccount userAccount = new UserAccount();
//                userAccount.setJaAccountid(UUIDUtils.getByUUId());
//                userAccount.setUserId(sysAppLogin.getUserId());
//                userAccount.setCurrency(0);
//                userAccount.setCurrency(0);
//                userAccount.setCreateTime(new Date());
//                userAccountService.insertUserAccount(userAccount);
//                SysAppLoginService.insertSysAppLogin(sysAppLogin);
//                writeJSON("注册成功", response, "200", "success");
//            } else {
//                writeJSON("验证码错误", response, "201", "success");
//            }
//        } else {
//            writeJSON("验证码超时", response, "201", "success");
//        }
//    }
//
//    /**
//     * 添加注册
//     */
//    @PostMapping("/addUserLogin")
//    @ApiOperation("添加教师")
//    @ApiImplicitParams({
//            @ApiImplicitParam(name = "userPhone", value = "登录账号", required = true, dataType = "String"),
//            @ApiImplicitParam(name = "userPassword", value = "登录密码", required = true, dataType = "String")})
//    public void addUserLogin(HttpServletResponse response, SysAppLogin sysAppLogin, String code) throws Exception {
//        SysAppLogin login = new SysAppLogin();
//        login.setUserPhone(sysAppLogin.getUserPhone());
//        List<SysAppLogin> logins = SysAppLoginService.selectSysAppLoginList(login);
//        if (logins.size() == 0) {
//            log.info(LogUtil.LogInfo("注册", new Date()));
//            String userIdJw = sysAppLogin.getUserIdJw();//教务主任用户ID
//            SysAppLogin sysUser = SysAppLoginService.selectSysAppLoginById(userIdJw);
//            if (sysUser != null) {
//                Integer teachers = sysUser.getTeachers();
//                Integer students = sysUser.getStudents();
//                Map<String, Object> map = new HashMap<>();
//                map.put("userPhone", sysAppLogin.getUserPhone());
//                SysAppLogin user = SysAppLoginService.selectByMap(map);
//                if (user == null) {
//                    String uuid = UUIDUtils.getByUUId();
//                    sysAppLogin.setUserId(uuid);
//                    sysAppLogin.setUserPassword(Token.encoderByMd5(sysAppLogin.getUserPassword()));
//                    sysAppLogin.setUserState(0);
//                    sysAppLogin.setUserIco("http://39.98.63.21:60/img/001.png");
////                    sysAppLogin.setUserCreatedate(new Timestamp(new Date().getTime()));
//                    sysAppLogin.setUserCreatedate(new Timestamp(System.currentTimeMillis()));
//                   /* UserAccount userAccount = new UserAccount();
//                    userAccount.setJaAccountid(UUIDUtils.getByUUId());
//                    userAccount.setUserId(sysAppLogin.getUserId());
//                    userAccount.setJaAmount(BigDecimal.valueOf(0));
//                    userAccount.setCurrency(0);
//                    userAccount.setCreateTime(new Date());
//                    userAccountService.insertUserAccount(userAccount);*/
//                    String type = sysAppLogin.getUserType();
//                    SysAppLogin sysUserJw = new SysAppLogin();
//                    sysUserJw.setUserId(userIdJw);
//                    if ("1".equals(type)) {//教师
//                        if (teachers - 1 >= 0) {
//                            sysUserJw.setTeachers(teachers - 1);
//                        } else {
//                            writeJSON("注册失败", response, "300", "教师不能分配");
//                            return;
//                        }
//                    } else if ("0".equals(type)) {
//                        if (students - 1 >= 0) {
//                            sysUserJw.setStudents(students - 1);
//                        } else {
//                            writeJSON("注册失败", response, "300", "学生不能分配");
//                            return;
//                        }
//                    }
//                    SysAppLoginService.updateSysAppLogin(sysUserJw);
//                    Integer classId = sysAppLogin.getClassId();
//                    sysAppLogin.setCustomerType("2");
//                    SysAppLoginService.insertSysAppLogin(sysAppLogin);
//                    UserAccount userAccount = new UserAccount();
//                    userAccount.setJaAccountid(UUIDUtils.getByUUId());
//                    userAccount.setUserId(uuid);
//                    userAccount.setCurrency(0);
//                    userAccount.setCurrency(0);
//                    userAccount.setCreateTime(new Date());
//                    userAccountService.insertUserAccount(userAccount);
//                    if ("1".equals(type)) {//教师
//                        teacherClassService.deleteTeacherClassByCIds(classId);
//                        TeacherClass teacherClass = new TeacherClass();
//                        teacherClass.setClassId(classId);
//                        teacherClass.setTeacherId(uuid);
//                        teacherClassService.insertTeacherClass(teacherClass);
//                    } else if ("0".equals(type)) {
//                        StudentClass studentClass = new StudentClass();
//                        studentClass.setClassId(classId);
//                        studentClass.setStudentId(uuid);
//                        studentClassService.insertStudentClass(studentClass);
//                    }
//                    writeJSON("注册成功", response, "200", "success");
//                } else {
//                    writeJSON("注册失败", response, "300", "用户名重复");
//                }
//            } else {
//                writeJSON("注册失败", response, "300", "教务主任不存在");
//            }
//        }else {
//            writeJSON("注册失败", response, "300", "该手机号已存在");
//        }
//    }


    /**
     * 查询教师和学生
     */
    @PostMapping("/userLoginList")
    public void userLoginList(HttpServletResponse response, SysAppLogin sysAppLogin, Integer pageNo, Integer pageSize) throws Exception {
        PageHelper.startPage(pageNo.intValue(), pageSize.intValue());
        List<SysAppLogin> list = SysAppLoginService.selectSysAppLoginList(sysAppLogin);
        writeJSON(new PageInfo<SysAppLogin>(list), response, "200", "success");
    }

    /**
     * 查询教师和学生
     */
    @PostMapping("/userLoginDel")
    public void userLoginDel(HttpServletResponse response, String id) throws Exception {
        SysAppLoginService.deleteSysAppLoginByIds(id);
        writeJSON("删除成功", response, "200", "success");
    }


    /**
     * 修改密码
     *
     * @param phone    用户名
     * @param password 密码
     * @return 结果
     */
//    @PostMapping("/changePassword")
//    @ApiOperation("修改密码")
//    @ApiImplicitParams({
//            @ApiImplicitParam(name = "phone", value = "登录账号", required = true, dataType = "String"),
//            @ApiImplicitParam(name = "password", value = "登录密码", required = true, dataType = "String")})
//    public void changePassword(HttpServletResponse response, String phone, String password) throws Exception {
//        log.info(LogUtil.LogInfo("修改密码", new Date()));
//        if (phone != null) {
//            SysAppLogin AppLogin = SysAppLoginService.selectByPhone(phone);
//            if (AppLogin != null) {
//                AppLogin.setUserPassword(Token.encoderByMd5(password));
//                SysAppLoginService.updateSysAppLoginbyuserPhone(AppLogin);
//                writeJSON("修改成功", response, "200", "success");
//            } else {
//                writeJSON("非法", response, "201", "success");
//            }
//        }
//    }

//    @GetMapping("/modifyVerification")
//    @ApiOperation("修改密码验证")
//    public void modifyVerification(HttpServletResponse response, String phone, String code) throws IOException {
//        log.info(LogUtil.LogInfo("修改密码验证" + phone, new Date()));
//        String s = redisTemplate.boundValueOps(phone).get();
//        if (s != null) {
//            if (code.equals(s)) {
//                writeJSON("验证成功", response, "200", "success");
//            } else {
//                writeJSON("验证码错误", response, "201", "success");
//            }
//        } else {
//            writeJSON("验证码超时", response, "201", "success");
//        }
//    }

//    @PostMapping("/sendSms")
//    @ApiOperation("发短信")
//    public void sendSms(HttpServletResponse response, String phone) throws Exception {
//        log.info(LogUtil.LogInfo("发送短信" + phone, new Date()));
//        if (phone != null) {
//            int math = (int) ((Math.random() * 9 + 1) * 100000);
//            Map<String, Object> map = new HashMap<>();
//            map.put("phone", phone);
//            if("18334722362".equals(phone)){
//                math=123456;
//            }
//            map.put("code", Integer.toString(math));
//            CommonRpc.setverCode(map);
//            redisTemplate.opsForValue().set(phone, Integer.toString(math));
//            redisTemplate.boundValueOps(phone).expire(180, TimeUnit.SECONDS);
//            writeJSON("发送成功请注意查收", response, "200", "success");
//        }
//    }
//
//    @GetMapping("/verifyAccount")
//    @ApiOperation("注册验证手机号是否注册过")
//    public void verifyAccount(HttpServletResponse response, String phone) throws IOException {
//        log.info(LogUtil.LogInfo("注册验证手机号是否注册过", new Date()));
//        String s = SysAppLoginService.checkPhoneUnique(phone);
//        if (s.equals("1")) {
//            writeJSON("手机号已注册", response, "201", "success");
//        } else {
//            writeJSON("手机号可以注册", response, "200", "success");
//        }
//    }

    /**
     * 新增保存学生班级关系
     */
    @PostMapping("/addStudent")
    @ResponseBody
    public void addStudent(StudentClass studentClass, HttpServletResponse response) throws IOException {
        studentClassService.insertStudentClass(studentClass);
        writeJSON(null, response, "200", "success");

    }

    /**
     * 新增保存教师班级关系
     */
    @PostMapping("/addTeacher")
    @ResponseBody
    public void addTeacher(TeacherClass teacherClass, HttpServletResponse response) throws IOException {
        teacherClassService.insertTeacherClass(teacherClass);
        writeJSON(null, response, "200", "success");

    }

    /**
     * 查询教师和学生
     */
    @PostMapping("/userLogins")
    public void userLogins(HttpServletResponse response, SysAppLogin sysAppLogin) throws Exception {
        List<SysAppLogin> list = SysAppLoginService.selectSysAppLoginList(sysAppLogin);
        writeJSON(list, response, "200", "success");
    }

    /**
     * 查询苹果充值达人币交易明细记录
     *
     * @param response
     * @param trxType 3金额- 5金额+
     * @param userId
     * @param pageSize
     * @param pageNum
     * @throws IOException
     */
    @GetMapping("/expensesRecord")
    public void expensesRecord(HttpServletResponse response, String trxType, String userId, Integer pageSize, Integer pageNum) throws IOException {
        log.info(LogUtil.LogInfo("查询苹果充值达人币交易明细记录", new Date()));
        CurrencyRecord record = new CurrencyRecord();
        record.setUserId(userId);
        record.setTrxType(trxType);
        if (pageNum != null && pageSize != null) {
            PageHelper.startPage(pageNum, pageSize);
        }
        List<CurrencyRecord> currencyRecords = currencyRecordService.selectCurrencyRecordList(record);
        writeJSON(currencyRecords, response, "200", "success");
    }
}